package com.dc.adaptor.convertor;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;

import com.dc.adaptor.InputAdaptor;
import com.dc.adaptor.persistance.Const;
import com.dc.adaptor.persistance.bean.SipContent;
import com.dc.adaptor.persistance.bean.SipRecvPack;
import com.dc.adaptor.step.InputAdaptorStep;
import com.dc.di.util.GUIDGen;

public class BaseMessageConvertor implements MessageConvertor {
	protected static final Log logger = LogFactory.getLog(BaseMessageConvertor.class);
	@Override
	public SipRecvPack convert(String message,InputAdaptor inputAdaptor) throws Exception {
		SipRecvPack sipRecvPack = new SipRecvPack();
		SipContent sipContent = new SipContent();
		sipContent.setContent(message);
		sipContent.setContentId(GUIDGen.getGUIDString());
		if(inputAdaptor!=null){
			sipRecvPack.setSenderId(inputAdaptor.getSource());
			sipRecvPack.setProtocolType(inputAdaptor.getType());
			if(inputAdaptor instanceof InputAdaptorStep){
				InputAdaptorStep inputAdaptorStep = (InputAdaptorStep)inputAdaptor;
				sipRecvPack.setJobName(inputAdaptorStep.getJobName());
				sipRecvPack.setJobInstanceid(inputAdaptorStep.getJobInstanceId());
			}
		}	
		sipRecvPack.setPackSn(GUIDGen.getGUIDString());
		sipRecvPack.setSipContent(sipContent);
		sipRecvPack.setFlag("0");
		sipRecvPack.setLast(true);
		sipRecvPack.setRecvtime(new Date());
		sipRecvPack.setReceiverId(System.getProperty("LICENSE"));
		sipRecvPack.setMessageType("xml");
		return sipRecvPack;
	}

	public List<RowMetaAndData> packToMetaData(SipRecvPack sipReceivePack){
		List<RowMetaAndData> list = new ArrayList<RowMetaAndData>();
		RowMetaAndData mData = new RowMetaAndData();		
		mData.addValue(new ValueMeta(Const.SOURCE_MESSAGE, ValueMetaInterface.TYPE_STRING), sipReceivePack.getSipContent().getContent());
		mData.addValue(new ValueMeta(Const.GLOBALBUSINESSID, ValueMetaInterface.TYPE_STRING), sipReceivePack.getMessageId());
		mData.addValue(new ValueMeta(Const.PACK_SN,ValueMetaInterface.TYPE_STRING), sipReceivePack.getPackSn());
		mData.addValue(new ValueMeta(Const.BUSINESSTYPE, ValueMetaInterface.TYPE_STRING), sipReceivePack.getBussinessCode());
		list.add(mData);
		return list;
	}

	@Override
	public SipRecvPack convert(String message, String fileName,
			InputAdaptor inputAdaptor) throws Exception {
		SipRecvPack sr = convert(message,inputAdaptor);
		sr.setGroupSn(fileName);
		return sr;
	}
}
